package book.service.impl;

import book.dao.reader.ReaderDao;
import book.dao.reader.impl.ReaderDaoImpl;
import book.util.MD5;
import book.pojo.vo.ReaderVO;
import book.pojo.Reader;
import book.service.IReaderService;


public class IReaderServiceImpl implements IReaderService {
    private ReaderDao readerDao = new ReaderDaoImpl();

    @Override
    public Reader login(ReaderVO readerVO) {
        //1、根据username查询用户
        Reader rtReader = readerDao.findReaderByUserName(readerVO.getUsername());
        if(null == rtReader){
            //用户名不正确
            return null;
        }
        //2、对登录密码进行加盐加密
        String loginPwd = MD5.getSaltMD5(readerVO.getPassword(),rtReader.getSalt());
        System.out.println("--- 调试信息 ---");
        System.out.println("输入用户名: " + readerVO.getUsername());
        System.out.println("输入原始密码: " + readerVO.getPassword());
        System.out.println("数据库盐值: " + rtReader.getSalt());

        String loginPwd2 = MD5.getSaltMD5(readerVO.getPassword(), rtReader.getSalt());
        System.out.println("加密后密码: " + loginPwd2);
        System.out.println("数据库存储密码: " + rtReader.getPassword());
        System.out.println("密码匹配结果: " + loginPwd2.equals(rtReader.getPassword()));
        System.out.println("----------------");
        //3、进行密码比对
        if(loginPwd.equals(rtReader.getPassword())){
            return rtReader;
        }
        //4、返回登录结果
        return null;
    }

    @Override
    public int addReader(Reader reader) {
        String salt = MD5.getSalt();
        String saltPwd = MD5.getSaltMD5(reader.getPassword(),salt);
        reader.setSalt(salt);
        reader.setPassword(saltPwd);
        return readerDao.addReader(reader);
    }
}
